//
//  NetworkHandler.m
//  UI20_NSURLSession
//
//  Created by 李劲成 on 16/4/6.
//  Copyright © 2016年 ljc. All rights reserved.
//

#import "NetworkHandler.h"

@interface NetworkHandler ()<NSURLSessionDataDelegate, NSURLSessionDataDelegate, NSURLSessionTaskDelegate>

// 用来接收从服务器发送来的数据.
@property (nonatomic, retain) NSMutableData *mData;

@property (nonatomic, assign) id <NetworkHandlerDelegate> delegate;

@end

@implementation NetworkHandler

+ (void)networkHanlerJSONWithURL:(NSString *)url delegate:(id<NetworkHandlerDelegate>)delegate {
    NetworkHandler *handler = [[NetworkHandler alloc]init];
    
    handler.delegate = delegate;
    
    // Core API:
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:handler     delegateQueue:[NSOperationQueue mainQueue]];
     NSURL *newUrl = [NSURL URLWithString:url];
    //向 Section 中添加 Task
    NSURLSessionDataTask *task = [session dataTaskWithURL:newUrl];
    [task resume];
}

#pragma mark - dataTask Delegate

/** 接收到响应 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    self.mData = [NSMutableData data];
    
    // 继续 data 任务.
    completionHandler(NSURLSessionResponseAllow);
    
}

/** 从服务器接收到数据.如果数据较大, 此方法会调用多次 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    
    // 拼接
    [self.mData appendData:data];
}

#pragma mark - taskDelegate
/** 当任务完成 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    
    // 数据解析(JSON)
    id result = [NSJSONSerialization JSONObjectWithData:self.mData options:NSJSONReadingMutableContainers error:nil];
    
    // 通过 delegate 回调
    if ([self.delegate respondsToSelector:@selector(didFinishCompletion:)]) {
        [self.delegate didFinishCompletion:result];
    }
    
}

@end
